#include "CVlcDelegator.h"
#include <algorithm>
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif

CVlcDelegator::CVlcDelegator(std::string sIP, int nAudioPort, int nVideoPort)
: m_cAudioSocket(sIP.c_str(), nAudioPort), m_cVideoSocket(sIP.c_str(), nVideoPort)
{
}
CVlcDelegator::~CVlcDelegator(void)
{
}


void CVlcDelegator::_sendAus(std::vector<CDynamicArray*>& aus, CVlcSocket& pSocket)
{
	CDynamicArray* sCurrentAU;
	//iterates over the AUs list
	for(unsigned int i=0; i<aus.size(); i++)  
	{
		sCurrentAU = aus.at(i);
		unsigned int nAlreadySent = 0;

		while (nAlreadySent < sCurrentAU->m_nSize)
		{
			int nBytesToSend = min(500, sCurrentAU->m_nSize - nAlreadySent);
			// sends each AU to VLC
			pSocket.sendPacket(sCurrentAU->m_cArray + nAlreadySent, nBytesToSend) ; 
			nAlreadySent += nBytesToSend;
		}
		delete sCurrentAU;
	}
	aus.clear();
}

void CVlcDelegator::outputAUs(IAUBuilder* cAUBuilder)
{
	// sends audio AU list
	_sendAus(cAUBuilder->m_audioAus, m_cAudioSocket); 
	// sends video AU list
	_sendAus(cAUBuilder->m_videoAus, m_cVideoSocket); 
}
